# coding: utf-8
from PySide6.QtCore import Qt, QUrl, QTimer, Signal
from PySide6.QtGui import QImage
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from qeventmanager import qevent_manager
from qfluentwidgets import BodyLabel, setFont, HyperlinkLabel, MaskDialogBase, FluentStyleSheet

from api import LoginCodeAPI, LoginAPI
from common import QRCodeHelper, signalBus
from components import ImageLabel


class QRDialog(MaskDialogBase):
    yesSignal = Signal()

    def __init__(self, title: str, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self.widget)
        self.titleLabel = QLabel(title, self.widget)
        self.yesButton = QPushButton('刷新二维码', self.widget)

        self.titleLabel.setWordWrap(True)
        self.yesButton.setFixedSize(150, 40)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.verticalLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignHCenter)
        self.verticalLayout.addSpacing(20)
        self.verticalLayout.addWidget(self.yesButton, 0, Qt.AlignmentFlag.AlignHCenter)

        self.setQss()

        self.yesButton.clicked.connect(self.__onYesButtonClicked)

    def setQss(self):
        self.windowMask.setObjectName('windowMask')
        self.titleLabel.setObjectName('titleLabel')
        FluentStyleSheet.MESSAGE_DIALOG.apply(self)

    def __onYesButtonClicked(self):
        self.setEnabled(False)
        self.yesSignal.emit()
        self.accept()


class UIQRCodeWidget:
    def setupUi(self, Form):
        self.verticalLayout = QVBoxLayout(Form)
        self.horizontalLayout = QHBoxLayout()
        self.titleLabel = BodyLabel('扫码登录', Form)
        self.contentLabel = BodyLabel('请使用', Form)
        self.downLabel = HyperlinkLabel(QUrl('https://www.qingshuxuetang.com/Download'), '手机客户端', Form)
        self.contentLabel_2 = BodyLabel(', 选择[我的] - [扫一扫]', Form)
        self.imageLabel = ImageLabel(Form)

        setFont(self.titleLabel, 24)
        self.imageLabel.setMinimumSize(200, 200)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignHCenter)

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        self.horizontalLayout.addWidget(self.contentLabel)
        self.horizontalLayout.addWidget(self.downLabel)
        self.horizontalLayout.addWidget(self.contentLabel_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.imageLabel, 0, Qt.AlignmentFlag.AlignHCenter)

        self.imageLabel.finished.connect(lambda: self.imageLabel.scaledToWidth(200))


class QRCodeWidget(QWidget, UIQRCodeWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.code = ''
        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.getQRCodeStatus)

    def showMessage(self):
        dialog = QRDialog(
            '二维码失效',
            self.imageLabel
        )
        if dialog.exec():
            self.initCode()
            self.timer.start()

    def initCode(self):
        qevent_manager.addTask(LoginCodeAPI.getQRCode, slot=self._onGetQRCode)

    def getQRCodeStatus(self):
        if not self.code:
            return
        qevent_manager.addTaskToPool(LoginCodeAPI.getQRCodeStatus, self.code, slot=self._onGetQRCodeStatus)

    def _onGetQRCode(self, result: dict):
        data = result.get('data')
        if not data:
            return

        self.code = data.get('code', '')
        qr_url = data.get('url', '')
        print(f'{qr_url}?code={self.code}')
        qevent_manager.addTaskToPool(QRCodeHelper.generate_qr_code_image, f'{qr_url}?code={self.code}',
                                     slot=self._onGenerateQRCodeImage)

    def _onGenerateQRCodeImage(self, image: QImage):
        self.imageLabel.setImage(image)
        self.timer.start()

    def _onGetQRCodeStatus(self, result: dict):
        data = result.get('data')
        if data == 2:
            self.showMessage()
            self.timer.stop()
        if data == 1:
            self.timer.stop()
            qevent_manager.addTask(LoginAPI.loginByQRCode, self.code, slot=self._onLoginByQRCode)

    def _onLoginByQRCode(self, headers: dict):
        LoginAPI.setCookies(headers)
        signalBus.loginSuccessSignal.emit()
